import json

from django.db.models import Sum
from django.shortcuts import render
from django.views import View

from cartapp import models
from cartapp.models import Cart
from goodsapp.models import Goods
from django.http import HttpResponseRedirect

from userapp.models import User


# Create your views here.

#展示购物车
class CartView(View):
    def get(self,request):
        user = request.session.get('user')
        user = User.objects.get(id=user.id)
        cart_list = Cart.objects.filter(user_id=user.id)
        num = 0
        sum = 0
        for cart in cart_list:
            sum =sum + cart.goods_price * cart.number
            num = num+cart.number

        return render(request,'cart.html',{'cart_list':cart_list,'num':num,'sum':sum,'user':user})


#直接加入购物车
class ZaddCartView(View):
    def get(self,request,good_id):
        user = request.session.get('user')
        print(user)
        goods = Goods.objects.get(id=good_id)
        if Cart.objects.filter(goods_name=goods.goods_name).exists():
            number = Cart.objects.get(goods_name=goods.goods_name).number
            number = number + 1
            Cart.objects.filter(goods_name=goods.goods_name).update(number=number)
        else:
            number = 1
            Cart.objects.create(goods_img=goods.goods_img,goods_name=goods.goods_name, number=number, goods_price=goods.goods_price,goods_detail=goods.goods_detail,
                                 user_id=user.id,goods_id=good_id)
        return HttpResponseRedirect('/cart/',)


#删除购物车
class DeleteCartView(View):
    def get(self,request,cart_id):
        Cart.objects.filter(id=cart_id).delete()
        user = request.session.get('user')

        return HttpResponseRedirect('/cart/')





# 购物车的加减
class DecquantityView(View):
    def get(self,request):
        return render(request, 'cart.html')

    def post(self,request):
        data = json.loads(request.body)  # 解析JSON
        product_id = data.get('productId')  # 获取productId
        number = data.get('number')
        Cart.objects.filter(id=product_id).update(number=number)
        return render(request,'cart.html')